package com.hewep.kit;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Properties;

import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class ConfigKit {
	static File file = new File(PathKit.getWebRootPath()+File.separator+"common.properties");
	static{
		if(!file.exists()){
			try {
				file.createNewFile();
				Properties prop = new Properties();
				prop.setProperty("local_port", "81");
				prop.setProperty("server_ip", "http://test.ccyoyo.com/");
				PropUtil.store(prop, file);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static Properties getConfig(){
		return PropUtil.load(file);
	}
	public static void setConfig(Properties prop){
		PropUtil.store(prop, file);
	}
	
	public static void put(String key, String value){
		Properties config = getConfig();
		config.put(key, value);
		setConfig(config);
	}
	public static int getInt(String key, int def){
		int temp = def;
		String value = PropUtil.getVaule(file, key);
		if(StrKit.notBlank(value)){
			temp = Integer.valueOf(value);
		}
		return temp;
	}
	
	public static String getStr(String key, String def){
		String temp = def;
		String value = PropUtil.getVaule(file, key);
		if(StrKit.notBlank(value)){
			temp = value;
		}
		return temp;
	}
	
	public static boolean getBoolean(String key, boolean def){
		boolean temp = def;
		String value = PropUtil.getVaule(file, key);
		if(StrKit.notBlank(value)){
			temp = Boolean.parseBoolean(value);
		}
		return temp;
	}
	
	public static int getOrderNo(String type){
		Record item = Db.findFirst("select * from config where item = ?", type);
		String newNo = type + "-" + DateUtils.getCurrDateFormat("yyMMdd")+"-0000";
		if(item != null){
			String preNo = item.getStr("value");
			String date = preNo.substring(preNo.indexOf("-")+1, preNo.lastIndexOf("-"));
			if(date.equals(DateUtils.getCurrDateFormat("yyMMdd"))){
				newNo = preNo;
			}
		}else{
			Record record = new Record();
			record.set("item", type);
			record.set("value", newNo);
			Db.save("config", record);
		}
		int sno = Integer.parseInt(newNo.substring(newNo.lastIndexOf("-")+1));
		return sno;
	}
	/**
	 * 根据单据类型生成流水单号
	 * @param type
	 * @return
	 */
	public static void updateOrderNo(String type, String orderNo){
		Db.update("update config set value = ? where item = ?", orderNo, type);
	}
}
